<template>
	<view class="video-device-form">
		<!-- 	<view class="header">
			<img src="../../static/arrow.png" alt="" class="back-img" />
			<text class="header-title">传感器调试</text>
		</view> -->

		<!-- 边设备信息 -->
		<view class="video-device-container">
			<view class="form-header">
				<text>边设备信息</text>
			</view>
			<view class="video-device-info">
				<view class="info-item">
					<text class="label">站房名称:</text>
					<uni-easyinput disabled v-model="station.stationName" :clearable="false"
						trim="true"></uni-easyinput>
				</view>
				<view class="info-item">
					<text class="label">设备IP:</text>
					<uni-easyinput disabled v-model="station.gatewayData.gatewayIP" :clearable="false" trim="true"
						class="ellipsis"></uni-easyinput>
				</view>
			</view>
		</view>

		<uni-popup style="width: 500px;" ref="inputDialog" type="dialog">
			<uni-popup-dialog style="width: 400px;" title="添加传感器" :before-close="true" @close="close()"
				@confirm="add()">
				<uni-forms style="width: 450px;" ref="mForm" :rules="rules" :modelValue="formData"
					class="form-container-box">
					<uni-forms-item label-width="80px" label="设备名称" required name="deviceName" class="info-item">
						<uni-easyinput v-model="formData.deviceName" placeholder="请输入设备名称" />
					</uni-forms-item>

					<!-- 			<uni-forms-item label-width="80px" label="设备标识" required name="deviceId" class="info-item">
						<uni-easyinput v-model="formData.deviceId" placeholder="请输入设备标识" />
					</uni-forms-item> -->

					<uni-forms-item label-width="80px" label="设备类型" required name="deviceType" class="info-item">
						<uni-data-select v-model="formData.deviceType" :localdata="deviceTypes" placeholder="请选择设备类型" />
					</uni-forms-item>

					<uni-forms-item label-width="80px" label="串口地址" required name="deviceAddress" class="info-item">
						<uni-easyinput v-model="formData.deviceAddress" placeholder="请输入串口地址" />
					</uni-forms-item>

					<uni-forms-item label-width="80px" label="COM口" required name="deviceType" class="info-item">
						<uni-data-select v-model="formData.devicePort" :localdata="portOptions" placeholder="请选择串口地址" />
					</uni-forms-item>
				</uni-forms>
			</uni-popup-dialog>
		</uni-popup>


		<!-- 端设备列表 -->
		<view class="end-device-list">
			<view class="header-box">
				<view class="flex">
					<view class="form-header">端设备列表</view>
					<button type="primary" class="add-camera-btn" @click="clickGetSensor()">
						<view class="icon-container">
							<image src="../../static/data.png" mode="" class="icon"></image>
						</view>获取数据
					</button>
				</view>
				<view class="flex">
					<button type="primary" class="scan-btn" @click="scanAdd()">扫码添加</button>
					<button type="primary" class="fetch-btn" @click="addDialog()">手动添加</button>
				</view>
			</view>

			<view>
			</view>


			<uni-popup style="width: 500px;" ref="editDialog" type="dialog">
				<uni-popup-dialog style="width: 400px;" title="编辑传感器" :before-close="true" @close="closeeEdit()"
					@confirm="confirmEdit()">
					<uni-forms style="width: 450px;" ref="mForm" :modelValue="editDevice" class="form-container-box">
						<uni-forms-item label-width="80px" label="设备名称" required name="name" class="info-item">
							<uni-easyinput :clearable="false" v-model="editDevice.name" />
						</uni-forms-item>

						<uni-forms-item label-width="80px" label="设备标识" required name="sn" class="info-item">
							<uni-easyinput v-model="editDevice.sn" placeholder="请输入设备标识" />
						</uni-forms-item>

						<uni-forms-item label-width="80px" label="设备类型" required name="type" class="info-item">
							<uni-data-select v-model="editDevice.type" :localdata="deviceTypes" placeholder="当前无设备类型" />
						</uni-forms-item>

						<uni-forms-item label-width="80px" label="设备地址" required name="comaddr" class="info-item">
							<uni-easyinput v-model="editDevice.comaddr" placeholder="请输入设备地址" />
						</uni-forms-item>

						<uni-forms-item label-width="80px" label="COM口" required name="comno" class="info-item">
							<uni-data-select v-model="editDevice.comno" :localdata="portOptions" placeholder="当前无串口" />
						</uni-forms-item>
						<!-- 	<uni-forms-item label="平台设备" required name="platformDeviceName" class="info-item">
							<uni-data-select v-model="editDevice.platformDeviceName" :localdata="platformOptions"
								placeholder="请选择平台设备名称" />
						</uni-forms-item> -->
					</uni-forms>
				</uni-popup-dialog>
			</uni-popup>


			<view class="end-device-container">
				<view class="device-item" v-for="(device, index) in deviceList" :key="index">
					<view class="device-header">
						<view class="device-text-container">
							<span class="device-text">{{ device.name }}</span>
						</view>
						<view class="device-buttons">
							<button type="primary" size="mini" class="delete-btn"
								@click="deleteDevice(device)">删除</button>
							<button type="primary" size="mini" class="edit-btn"
								@click="showEditDialog(device)">编辑</button>
						</view>
					</view>
					<view class="device-content">
						<view class="device-detail" v-for="(detail, dIndex) in device.points" :key="dIndex">
							<text class="text-detail">{{ detail.name }}: </text>
							<text v-if="detail.value ===''" class="text-detail"></text>
							<text v-else="detail.value "
								class="text-detail">{{ detail.value }}&nbsp;{{detail.unit}}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 按钮栏 -->
		<!-- <view class="button-bar"> -->
		<!-- <button class="import-btn">导入平台台账</button> -->
		<button type="primary" class="btnl" @click="doAddSensor()">
			<view class="icon-container">
				<image src="../../static/check.png" mode="" class="icon"></image>
			</view>保存配置
		</button>
		<!-- </view> -->
	</view>


</template>

<script setup lang="ts">
	import { ref, onMounted, reactive } from 'vue'
	import { WEB_URL } from '../../config/global';
	import { onLoad } from '@dcloudio/uni-app';
	const mForm = ref()
	const deviceList = ref([])
	const editDevice = ref()
	const editDialog = ref()
	const inputDialog = ref()
	const station = ref()
	const addDialogRef = ref()
	const formData = ref({
		deviceName: "",
		deviceId: "",
		deviceType: "",
		deviceAddress: "",
		devicePort: "",
	})



	// 模拟数据
	// const mockDeviceList = [
	// 	{
	// 		id: '1',
	// 		name: '传感器A',
	// 		sn: 'SN123456789',
	// 		type: '00', // 温湿度
	// 		comaddr: '/dev/ttyUSB0',
	// 		comno: 'COM1',
	// 		points: [
	// 			{ name: '温度', value: '25℃', unit: '℃' },
	// 			{ name: '湿度', value: '60%', unit: '%' }
	// 		]
	// 	},
	// 	{
	// 		id: '2',
	// 		name: '传感器B士大夫士大夫敢死队手动阀手动阀犬瘟热犬瘟热 发多少个的风格',
	// 		sn: 'SN987654321',
	// 		type: '01', // 水浸
	// 		comaddr: '/dev/ttyUSB1',
	// 		comno: 'COM2',
	// 		points: [
	// 			{ name: '水位', value: '正常', unit: '' }
	// 		]
	// 	},
	// 	{
	// 		id: '3',
	// 		name: '传感器C',
	// 		sn: 'SN111222333',
	// 		type: '02', // 烟感
	// 		comaddr: '/dev/ttyUSB2',
	// 		comno: 'COM3',
	// 		points: [
	// 			{ name: '烟雾浓度', value: '低', unit: '' }
	// 		]
	// 	}
	// ];


	const deviceTypes = [
		{
			text: '温湿度',
			value: '00'
		},
		{
			text: '水浸',
			value: '01'
		},
		{
			text: '烟感',
			value: '02'
		},
		{
			text: '气体传感器',
			value: '03'
		},
		{
			text: '门磁',
			value: '04'
		},
		{
			text: '水位传感器',
			value: '05'
		},
		{
			text: '风机',
			value: '06'
		},
		{
			text: '水泵',
			value: '07'
		},
		{
			text: '蓄电池',
			value: '08'
		},
		{
			text: '空调控制器',
			value: '09'
		},

	];

	const protocolTypes = [
		{
			text: '无线Lora',
			value: '00'
		},
		{
			text: '有线modbus2型',
			value: '01'
		},
		{
			text: '有线modbus7型',
			value: '02'
		},
		{
			text: 'TOPUNB',
			value: '03'
		}
	];

	const portOptions = [
		{
			text: 'COM1',
			value: 'COM1'
		},
		{
			text: 'COM2',
			value: 'COM2'
		},
		{
			text: 'COM3',
			value: 'COM3'
		},
		{
			text: 'COM4',
			value: 'COM4'
		},
		{
			text: 'COM5',
			value: 'COM5'
		},
		{
			text: 'COM6',
			value: 'COM6'
		}
	];

	const rules = {
		deviceName: {
			rules: [{
				required: true,
				errorMessage: '设备名称不能为空'
			}]
		},
		deviceId: {
			rules: [{
				required: true,
				errorMessage: '设备标识不能为空'
			}]
		},
		deviceType: {
			rules: [{
				required: true,
				errorMessage: '请选择设备类型'
			}]
		},
		deviceAddress: {
			rules: [{
				required: true,
				errorMessage: '串口地址不能为空'
			}]
		},
		devicePort: {
			rules: [{
				required: true,
				errorMessage: '请选择COM口'
			}]
		}
	};


	const showEditDialog = (device) => {
		editDevice.value = device
		editDialog.value.open()
	}

	const deleteDevice = (device) => {
		uni.showModal({
			title: '提示',
			content: '是否确认删除?删除后需保存配置才可生效',
			confirmText: "确定",
			cancelText: "取消",
			showCancel: true,
			success: (res) => {
				if (res.confirm) {
					deviceList.value = deviceList.value.filter((item) => {
						return item.sn !== device.sn
					})
				}
			}
		})
	}

	const doAddSensor = async () => {
		uni.showModal({
			title: '提示',
			content: '是否确认保存配置?',
			confirmText: "确定",
			cancelText: "取消",
			showCancel: true,
			success: (res) => {
				if (res.confirm) {
					let array = []
					//json序列化深拷贝
					//构造参数
					for (let i = 0; i < deviceList.value.length; i++) {
						let device = JSON.parse(JSON.stringify({}));
						device.name = deviceList.value[i].name
						device.type = deviceList.value[i].type
						device.sn = deviceList.value[i].sn
						device.comno = deviceList.value[i].comno
						device.comaddr = deviceList.value[i].comaddr
						array.push(device)
					}
					let param = { data: array }
					uni.request({
						url: WEB_URL + '/app/addSensor',
						data: param,
						method: 'POST',
						header: {
							'Content-Type': 'application/json'
						},
						dataType: 'json',
						success: async (res) => {
							if (res.data.code === 0) {
								uni.showToast({
									title: '保存成功',
									icon: 'success'
								})

								await getSensor()

							} else {
								uni.showModal({
									title: '提示',
									content: res.data.message,
									confirmText: "确定",
									showCancel: false,
								})
							}
						},
						fail: (err) => {
							uni.showModal({
								title: '提示',
								content: '保存失败，系统异常',
								confirmText: "确定",
								showCancel: false,
							})
						},
					})
				}
			}
		})

	}


	const open = () => {
		inputDialog.value.open()
	}



	const closeeEdit = () => {
		editDialog.value.close()
	}

	const confirmEdit = () => {
		uni.showToast({
			title: '修改成功',
			icon: 'success'
		})
		editDialog.value.close()
	}

	const close = () => {
		formData.value.deviceName = ""
		formData.value.deviceId = ""
		formData.value.deviceType = ""
		formData.value.deviceAddress = ""
		formData.value.devicePort = ""
		inputDialog.value.close()
	}

	const add = async () => {
		const valid = await mForm.value.validate();
		if (valid) {
			console.log('deviceList.value', deviceList.value);
			let param = {
				name: formData.value.deviceName,
				sn: formData.value.deviceId,
				comaddr: formData.value.deviceAddress,
				type: formData.value.deviceType,
				comno: formData.value.devicePort
			}
			deviceList.value.push(param)
			close()
		}
	}

	const addDialog = () => {
		// uni.navigateTo({
		// 	url: "/pages/addSensor/addSensor"
		// })
		inputDialog.value.open()
	}

	//扫码添加
	const scanAdd = () => {
		uni.scanCode({
			onlyFromCamera: true,
			success(res) {
				let devieType = res.result.slice(2, 4)
				let protocolType = res.result.slice(4, 6)
				let sn = res.result.slice(5, 16)
				let param = {
					name: '',
					sn: sn,
					comaddr: '',
					type: devieType,
					comno: ''
				}
				deviceList.value.push(param)
				uni.showToast({
					title: '扫码添加成功',
					icon: 'success'
				})
			}
		})
	}


	onLoad(async (options) => {
		if (!Object.keys(options).length == 0) {
			station.value = JSON.parse(decodeURIComponent(options.item))
			console.log('station.value', station.value);
		}

		// station.value = {
		// 	stationName: '测试',
		// 	videoData: {
		// 		videoPort: 8000,
		// 		videoUsername: "admin",
		// 		videoPassword: "njzt12345"
		// 	},
		// 	gatewayData: {
		// 		gatewayIP: "192.168.1.168",
		// 		gatewayPort: 8000,
		// 		gatewayPassword: 'njzt12345'
		// 	}
		// }

		await getSensor()



	});


	const clickGetSensor = async () => {

		uni.showModal({
			title: '提示',
			content: '是否确认获取数据？确认后，您未保存的传感器数据将会重置',
			confirmText: "确定",
			cancelText: "取消",
			showCancel: true,
			success: async (res) => {
				if (res.confirm) {
					await getSensor()
					uni.showToast({
						title: '获取成功',
						icon: 'success'
					})
				}
			}
		})
	}

	const getSensor = () => {

		// 模拟数据
		// deviceList.value = mockDeviceList;
		deviceList.value = [];

		return new Promise((resolve, reject) => {
			uni.request({
				url: WEB_URL + '/app/getSensor',
				method: 'GET',
				success: (res) => {
					if (res.data.code === 0) {
						if (res.data.data === null || res.data.data === undefined) {
							deviceList.value = []
						} else {
							deviceList.value = res.data.data
						}
						resolve('suc');
					} else {
						uni.showModal({
							title: '提示',
							content: res.data.message,
							confirmText: "确定",
							showCancel: false,
						})
					}
				},
				fail(err) {
					uni.showModal({
						title: '提示',
						content: '系统错误',
						confirmText: "确定",
						showCancel: false,
					})
					reject('err')
				}
			})
		})
	}
</script>

<style>
	/* 基本样式 */
	.video-device-form {
		padding: 20px;
		background-color: #f7f7f7;
		/* border-radius: 8px; */
		height: 100vh;

	}

	.text-detail {
		font-style: normal;
		font-size: 14px;
	}

	.header {
		/* border: 1px solid red; */
		display: flex;
		justify-content: center;
		align-items: center;

		padding: 20px 0;
		position: relative;
		position: fixed;

		top: 0;
		left: 0;
		width: 100%;
		background-color: #f7f7f7;
		z-index: 1000;

	}

	.back-img {
		position: absolute;
		left: 0;
	}

	.header-title {
		font-size: 24px;
		color: #666;
	}

	.video-device-container {
		/* border: 1px solid red; */
		/* margin-top: 40px; */
		padding: 20px;
		background-color: #fff;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		border-radius: 5px;
	}

	.header-box {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.form-header {
		font-size: 24px;
		color: #666;
		margin-right: 20px;
	}

	.header-btn {
		display: flex;
		align-items: center;

	}

	.invider {
		width: 20px;
	}

	/* 视频设备信息样式 */
	.video-device-info {
		margin-top: 15px;
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 20px;
		/* 项目之间的间距 */
		margin-bottom: 5px;
	}

	.info-item {
		flex: 1 1 calc(50% - 20px);
		/* 每个项目占50%宽度减去间距 */
		display: flex;
		align-items: center;
		/* 垂直居中对齐 */
		gap: 10px;
	}

	.ellipsis {
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
		max-width: 200px;
		/* 根据需要调整 */
	}

	/* 当前行只有最后一个输入框时，让它占一半 */
	.video-device-info>.last-item:last-child {
		flex: 1 1 calc(50% - 20px);
	}

	.form-label {
		font-size: 15px;
		/* color: #666; */
		width: 80px;
		text-align: right;
		flex-shrink: 0;
		padding-right: 5px;
	}

	.label {
		font-size: 17px;
		color: #666;
		width: 80px;
		text-align: right;
		flex-shrink: 0;
		padding-right: 5px;
	}

	.input {
		padding: 8px;
		border: 1px solid #ddd;
		border-radius: 4px;
		font-size: 18px;

	}

	.end-device-list {
		margin-top: 20px;
		background-color: #fff;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		border-radius: 5px;
		padding: 20px;
		margin-bottom: 20px;
	}

	.end-device-container {
		margin-top: 20px;
		/* border: 1px solid red; */
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 10px;
	}

	.device-item {
		border: 1px solid #ddd;
		border-radius: 8px;
		/* padding: 10px; */
		margin-bottom: 10px;
	}

	.device-header {
		/* display: flex;
		justify-content: space-between;
		align-items: center; */

		display: grid;
		grid-template-columns: repeat(2, 1fr);
		padding: 10px 0;
		background-color: #f3fbfb;
		border-top-right-radius: 8px;
		border-top-left-radius: 8px;
	}

	.device-text-container {
		flex: 1;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}

	.device-text {
		font-size: 16px;
		margin: 0 10px;
	}


	.device-buttons {
		flex: 1;
		display: flex;
		justify-content: flex-end;
		/* gap: 10px; */
	}

	.edit-btn {
		font-size: 16px;
		background-color: #48b0b1 !important;
		/* color: white; */
		/* padding: 0 8px; */
		border-radius: 4px;
	}

	.delete-btn {
		font-size: 16px;
		background-color: #EA3F4A !important;
		border-radius: 4px;
	}

	.more-btn {
		font-size: 16px;
		background-color: #5a79ff !important;
		border-radius: 4px;
	}

	.device-content {
		margin-top: 10px;
	}


	.device-detail {
		display: flex;
		align-items: center;
		padding: 5px 10px;
		margin-bottom: 5px;
	}

	/* 固定在底部的按钮栏 */
	.button-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		justify-content: space-around;
		background-color: #fff;
		padding: 20px;
		z-index: 1000;
	}

	.flex {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.import-btn {
		background-color: #48b0b1 !important;
	}

	.scan-btn {
		border-radius: 5px;
		background-color: #5a79ff !important;
		margin-right: 10px;
	}

	.save-setting-btn {
		border-radius: 5px;
		background-color: #5a79ff !important;
		/* margin-right: 10px; */
	}

	.fetch-btn {
		border-radius: 5px;
		background-color: #07c160 !important;
	}

	.btn-container {
		border-radius: 5px;
		padding: 0 10px;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #5a79ff !important;

		.icon-container {
			width: 20px;
			height: 20px;
		}

		.icon {
			width: 100%;
			height: 100%;
		}
	}

	.btn-container-fetch {
		border-radius: 5px;
		padding: 0 10px;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #07c160 !important;

		.icon-container {
			width: 20px;
			height: 20px;
		}

		.icon {
			width: 100%;
			height: 100%;
		}
	}

	.btnl {
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 4px;
		font-size: 16px;
		width: 150px;
	}

	.add-channel-btn,
	.add-camera-btn {
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 4px;
		font-size: 16px;
	}

	.add-channel-btn {
		background-color: #48b0b1 !important;
	}

	.add-camera-btn {
		background-color: #07c160 !important;
	}

	.icon-container {
		width: 20px;
		height: 20px;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-right: 10px;
	}

	.icon {
		width: 100%;
		height: 100%;
	}
</style>